﻿
// StoreSCUDlg.cpp: 实现文件
//

#include "pch.h"
#include "framework.h"
#include "StoreSCU.h"
#include "StoreSCUDlg.h"
#include "afxdialogex.h"
#include "Utilities.h"

#include "CDcmStoreSCU.h"

#ifdef _DEBUG
#define new DEBUG_NEW
#endif


// 用于应用程序“关于”菜单项的 CAboutDlg 对话框

class CAboutDlg : public CDialogEx
{
public:
	CAboutDlg();

// 对话框数据
#ifdef AFX_DESIGN_TIME
	enum { IDD = IDD_ABOUTBOX };
#endif

	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV 支持

// 实现
protected:
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialogEx(IDD_ABOUTBOX)
{
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
END_MESSAGE_MAP()


// CStoreSCUDlg 对话框
static int CALLBACK BrowseCallbackProc(HWND hWnd, UINT uMsg, LPARAM, LPARAM lpData)
{
	if (uMsg == BFFM_INITIALIZED)
	{
		CTreeCtrl   treePath;
		HTREEITEM   hItemSel;
		::SendMessage(hWnd, BFFM_SETSELECTION, TRUE, lpData);
		treePath.SubclassWindow(::GetDlgItem(hWnd, 0x3741));
		hItemSel = treePath.GetSelectedItem();
		treePath.Expand(hItemSel, TVE_COLLAPSE);
		treePath.UnsubclassWindow();
	}
	return 0;
}


CStoreSCUDlg::CStoreSCUDlg(CWnd* pParent /*=nullptr*/)
	: CDialogEx(IDD_STORESCU_DIALOG, pParent)
	, m_localAET(_T("xg-storescu"))
	, m_remoteAET(_T("xg-storescp"))
	, m_serverIP(_T("127.0.0.1"))
	, m_port(3000)
{
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
	m_brBlack.CreateSolidBrush(RGB(0, 0, 0));
}

void CStoreSCUDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
	DDX_Text(pDX, IDC_EDIT_STORESCU_LAET, m_localAET);
	DDX_Text(pDX, IDC_EDIT_STORESCU_RAET, m_remoteAET);
	DDX_Text(pDX, IDC_EDIT_STORESCU_RIP, m_serverIP);
	DDX_Text(pDX, IDC_EDIT_STORESCU_RPORT, m_port);
	DDX_Control(pDX, IDC_COMBO_LL, m_cmbLL);
	DDX_Control(pDX, IDC_LIST_FILE, m_lstFiles);
	DDX_Control(pDX, IDC_EDIT_STORESCU_LOG, m_log);
}

BEGIN_MESSAGE_MAP(CStoreSCUDlg, CDialogEx)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_WM_CTLCOLOR()
	ON_MESSAGE(UM_ADD_LOG, &CStoreSCUDlg::OnAddLog)
	ON_BN_CLICKED(IDC_BUTTON_STORESCU_OPENFILE, &CStoreSCUDlg::OnBnClickedButtonStorescuOpenfile)
	ON_BN_CLICKED(IDC_BUTTON_STORESCU_OPENDIR, &CStoreSCUDlg::OnBnClickedButtonStorescuOpendir)
	ON_BN_CLICKED(IDC_BUTTON_STORESCU_CLEARFILE, &CStoreSCUDlg::OnBnClickedButtonStorescuClearfile)
	ON_BN_CLICKED(IDC_BUTTON_STORESCU_SEND, &CStoreSCUDlg::OnBnClickedButtonStorescuSend)
	ON_BN_CLICKED(IDC_BUTTON_STORESCU_CLRLOG, &CStoreSCUDlg::OnBnClickedButtonStorescuClrlog)
	ON_BN_CLICKED(IDC_BUTTON_STORESCU_ECHO, &CStoreSCUDlg::OnBnClickedButtonStorescuEcho)
END_MESSAGE_MAP()


// CStoreSCUDlg 消息处理程序

BOOL CStoreSCUDlg::OnInitDialog()
{
	CDialogEx::OnInitDialog();

	// 将“关于...”菜单项添加到系统菜单中。

	// IDM_ABOUTBOX 必须在系统命令范围内。
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != nullptr)
	{
		BOOL bNameValid;
		CString strAboutMenu;
		bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
		ASSERT(bNameValid);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// 设置此对话框的图标。  当应用程序主窗口不是对话框时，框架将自动
	//  执行此操作
	SetIcon(m_hIcon, TRUE);			// 设置大图标
	SetIcon(m_hIcon, FALSE);		// 设置小图标

	// TODO: 在此添加额外的初始化代码
	addLog(_T("程序启动"));
	m_cmbLL.AddString(_T("调试"));
	m_cmbLL.AddString(_T("通知"));
	m_cmbLL.AddString(_T("警告"));
	m_cmbLL.AddString(_T("错误"));
	m_cmbLL.SetCurSel(1);

	return TRUE;  // 除非将焦点设置到控件，否则返回 TRUE
}

void CStoreSCUDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialogEx::OnSysCommand(nID, lParam);
	}
}

// 如果向对话框添加最小化按钮，则需要下面的代码
//  来绘制该图标。  对于使用文档/视图模型的 MFC 应用程序，
//  这将由框架自动完成。

void CStoreSCUDlg::OnPaint()
{
	if (IsIconic())
	{
		CPaintDC dc(this); // 用于绘制的设备上下文

		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

		// 使图标在工作区矩形中居中
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// 绘制图标
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialogEx::OnPaint();
	}
}

//当用户拖动最小化窗口时系统调用此函数取得光标
//显示。
HCURSOR CStoreSCUDlg::OnQueryDragIcon()
{
	return static_cast<HCURSOR>(m_hIcon);
}



HBRUSH CStoreSCUDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
	HBRUSH hbr = CDialogEx::OnCtlColor(pDC, pWnd, nCtlColor);

	// TODO:  在此更改 DC 的任何特性
	if (pWnd && pWnd->m_hWnd == m_log.GetSafeHwnd())
	{
		pDC->SetBkColor(0);
		pDC->SetTextColor(RGB(220, 220, 220));
		return m_brBlack;
	}

	// TODO:  如果默认的不是所需画笔，则返回另一个画笔
	return hbr;
}

LRESULT CStoreSCUDlg::OnAddLog(WPARAM wParam, LPARAM lParam)
{
	CString logStr = (LPCTSTR)wParam;

	if (m_log.m_hWnd && IsWindow(m_log.m_hWnd))
	{
		int nLmt = m_log.GetLimitText();
		int nTextLength = m_log.GetWindowTextLength();
		if ((int)(nTextLength + logStr.GetLength()) >= nLmt)
		{
			int nPos = m_log.LineIndex(100);
			m_log.SetSel(0, nPos);
			m_log.ReplaceSel(_T(""), FALSE);
		}

		m_log.SetSel(nTextLength, nTextLength);
		m_log.ReplaceSel(logStr);
		m_log.PostMessage(EM_SETSEL, -1, -1);
	}

	return 0;
}

void CStoreSCUDlg::addLog(CString str)
{
	std::string timeStr = GetTimeStr(5);
	CString logStr;
	logStr.Format(_T("[%s][App] %s\r\n"), timeStr.c_str(), str);
	::SendMessage(this->m_hWnd, UM_ADD_LOG, (WPARAM)(LPCTSTR)logStr, 0);
}


void CStoreSCUDlg::OnBnClickedButtonStorescuOpenfile()
{
	UpdateData();

	CString strFilter;
	strFilter = _T("All files(*.*)|*.*|DCM file(*.dcm;*.dic)|*.dcm;*.dic||");
	CFileDialog dlg(TRUE, NULL, NULL,
		OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT | OFN_ALLOWMULTISELECT,
		strFilter, NULL);

	TCHAR *pszFile = new TCHAR[MAX_PATH * 500];
	memset(pszFile, 0, sizeof(TCHAR)*MAX_PATH * 500);
	dlg.m_ofn.lpstrFile = pszFile;
	dlg.m_ofn.nMaxFile = MAX_PATH * 500;
	dlg.m_ofn.lpstrFile[0] = '\0';

	m_lstFiles.ResetContent();
	m_files.clear();

	if (dlg.DoModal() == IDOK)
	{
		CString strFile;
		POSITION pos = dlg.GetStartPosition();
		while (pos != NULL)
		{
			strFile = dlg.GetNextPathName(pos);
			m_files.push_back((LPCTSTR)strFile);
			m_lstFiles.AddString(strFile);
			UpdateWidth(strFile);
		}

		CString txt;
		txt.Format(_T("源文件: %d"), m_lstFiles.GetCount());
		GetDlgItem(IDC_STATIC_FILE)->SetWindowText(txt);
	}

	delete[] pszFile;
}

void CStoreSCUDlg::UpdateWidth(LPCTSTR lpszItem)
{
	CFont *pFont = m_lstFiles.GetFont();
	CClientDC dc(this);
	dc.SelectObject(pFont);
	CSize sz = dc.GetTextExtent(lpszItem, _tcslen(lpszItem));
	sz.cx += (3 * ::GetSystemMetrics(SM_CXBORDER));
	if (sz.cx > m_nListWidth)
	{
		m_nListWidth = sz.cx + 10;
		m_lstFiles.SetHorizontalExtent(m_nListWidth);
	}
}


void CStoreSCUDlg::EnumFileInDir(CString dir, std::vector<CString>& vec, LPCTSTR ext /*= NULL*/)
{
	CFileFind finder;

	if (dir[dir.GetLength() - 1] != _T('\\')) dir += _T("\\");

	if (finder.FindFile(dir + _T("*.*")))
	{
		BOOL bFind = FALSE;
		do
		{
			bFind = finder.FindNextFile();

			if (finder.IsDots())
				continue;
			else if (finder.IsDirectory())
			{
				CString strDir = finder.GetFilePath();
				strDir += _T("\\");
				EnumFileInDir(strDir, vec, ext);
			}
			else
			{
				CString fnext;
				CString fn = finder.GetFileName();
				int pos = fn.ReverseFind(_T('.'));
				if (pos != -1)
				{
					CString strExt = ext;
					fnext = fn.Mid(pos);
					if (fnext.CompareNoCase(strExt) == 0)
						vec.push_back(finder.GetFilePath());
				}
			}

		} while (bFind);
	}
}

void CStoreSCUDlg::OnBnClickedButtonStorescuOpendir()
{
	UpdateData();

	TCHAR           szFolderPath[MAX_PATH] = { 0 };

	BROWSEINFO      sInfo;
	::ZeroMemory(&sInfo, sizeof(BROWSEINFO));
	sInfo.pidlRoot = 0;
	sInfo.lpszTitle = _T("选择文件夹：");
	sInfo.ulFlags = BIF_BROWSEFORCOMPUTER | BIF_NEWDIALOGSTYLE | BIF_RETURNONLYFSDIRS;
	sInfo.lpfn = BrowseCallbackProc;
	sInfo.lParam = (LPARAM)(LPCTSTR)m_dir;

	// 显示文件夹选择对话框  
	LPITEMIDLIST lpidlBrowse = ::SHBrowseForFolder(&sInfo);
	if (lpidlBrowse != NULL)
	{
		if (::SHGetPathFromIDList(lpidlBrowse, szFolderPath))
		{
			m_dir = szFolderPath;
			if (m_dir.Right(1) != _T("\\"))
				m_dir += _T("\\");

			UpdateData(FALSE);
		}

		::CoTaskMemFree(lpidlBrowse);

		if (!m_dir.IsEmpty())
		{
			m_lstFiles.ResetContent();
			m_files.clear();

			std::vector<CString> vecDcmFile;
			EnumFileInDir(m_dir, vecDcmFile, _T(".dcm"));
			for (int i = 0; i < vecDcmFile.size(); i++)
			{
				m_lstFiles.AddString(vecDcmFile.at(i));
				UpdateWidth(vecDcmFile.at(i));
				m_files.push_back((LPCTSTR)vecDcmFile.at(i));
			}

			CString txt;
			txt.Format(_T("源文件: %d"), m_lstFiles.GetCount());
			GetDlgItem(IDC_STATIC_FILE)->SetWindowText(txt);
		}
	}
}


void CStoreSCUDlg::OnBnClickedButtonStorescuClearfile()
{
	m_files.clear();
	m_lstFiles.ResetContent();

	CString txt;
	txt.Format(_T("源文件: 0"));
	GetDlgItem(IDC_STATIC_FILE)->SetWindowText(txt);
}


void CStoreSCUDlg::OnBnClickedButtonStorescuSend()
{
	UpdateData();

	if (m_remoteAET.IsEmpty() || m_serverIP.IsEmpty() || m_localAET.IsEmpty())
	{
		MessageBox(_T("请正确填写DICOM网络参数."));
		return;
	}

	if (m_files.size() <= 0)
	{
		MessageBox(_T("请选择文件!"));
		return;
	}

	CDcmStoreSCU scu;
	int ll = m_cmbLL.GetCurSel();
	SCUParam param;
	param.remoteAET = m_remoteAET;
	param.serverIP = m_serverIP;
	param.hLogWnd = GetSafeHwnd();
	param.loglevel = ll;
	param.localAET = m_localAET;
	param.port = m_port;
	scu.SetParam(param);

	int sendCount = 0;

	while (m_files.size() > sendCount) {
		std::vector<std::string> vec;
		vec.reserve(100);
		int count = 100;
		if (m_files.size() - sendCount < 100) count = m_files.size() - sendCount;

		vec.assign(m_files.begin() + sendCount, m_files.begin() + sendCount + count);

		scu.Send(vec);
		sendCount += count;
	}
}


void CStoreSCUDlg::OnBnClickedButtonStorescuEcho()
{
	UpdateData();

	if (m_remoteAET.IsEmpty() || m_serverIP.IsEmpty() || m_localAET.IsEmpty())
	{
		MessageBox(_T("请正确填写DICOM网络参数."));
		return;
	}

	CDcmStoreSCU scu;
	int ll = m_cmbLL.GetCurSel();
	SCUParam param;
	param.remoteAET = m_remoteAET;
	param.serverIP = m_serverIP;
	param.hLogWnd = GetSafeHwnd();
	param.loglevel = ll;
	param.localAET = m_localAET;
	param.port = m_port;

	scu.SetParam(param);
	scu.Echo();
}


void CStoreSCUDlg::OnBnClickedButtonStorescuClrlog()
{
	m_log.SetSel(0, -1);
	m_log.ReplaceSel(_T(""), FALSE);
}

